package com.dongdongshop.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.dongdongshop.util.RedisUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@DubboService
@RocketMQMessageListener(topic = "VERIFICATION",consumerGroup = "VerificationCodeConsumer")
public class VerificationCodeServiceImpl implements RocketMQListener<String> {
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public void main(String[] args_) throws Exception {
        RedisTemplate redis = RedisUtil.redis;
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dysmsapi20170525.Client client = VerificationCodeServiceImpl.createClient("LTAI4GCbdwnjCGwQj9Z3tr3N", "27ih4pc1W1tqey9X4mmCy1JUotAX7L");
        String s = RandomUtil.randomNumbers(4);
        redis.boundValueOps(args.get(0)).set(s);
        redis.expire(args.get(0),1, TimeUnit.MINUTES);
        System.out.println("验证码:["+s+"],1分钟失效!");
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(args.get(0))
                .setSignName("东科创想111")
                .setTemplateCode("SMS_162522027")
                .setTemplateParam("{\"sms_code\":\""+s+"\"}");
//         复制代码运行请自行打印 API 的返回值
        client.sendSms(sendSmsRequest);
    }
    public static  void verificationCode() throws Exception {
        String[] arr = {"123","abc"};
        new VerificationCodeServiceImpl().main(arr);
    }

    @Override
    public void onMessage(String s) {
        String[] strArr = {s};
        try {
            new VerificationCodeServiceImpl().main(strArr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
